package project.shared.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

//import client.GUI.ErrorMessageGUI;

import project.server.util.Logger;

public class Config {
	/** The configuration file. */
	private File file;
	
	/** The ip to use when connecting to the server. */
	private String ip;
	
	/** The port to use when connecting to the server. */
	private int port;
	
	/** Time to wait until the game starts. */
	private int waitBeforeReady;
	
	/** The Logger for logging errors. */
	private Logger logger = null;
	
	/** The helper string that is used to parse config file. */
	private String helper;
	
	
	public Config(String fileLoc, Logger log) throws FileNotFoundException{
		file = new File(fileLoc);
		this.logger = log;
		getConfig();
	}
	
	public Config(String fileLoc) throws FileNotFoundException{
		file = new File(fileLoc);
		getConfig();
	}
	
	public void getConfig() throws FileNotFoundException{
		FileReader fr = new FileReader(file);
		BufferedReader br = new BufferedReader(fr);
		while(true){
			String line = null;
			try{
				line = br.readLine();
			}catch(IOException e){
				if(logger != null){
					logger.logError("Config readLine() error");
				}else{
//					new ErrorMessageGUI("Config readLine() error");
				}
			}
			if(line != null){
				helper = "ip";
				if(line.startsWith(helper)){
					ip = line.split("=")[1];
				}
				helper = "port";
				if(line.startsWith(helper)){
					port = Integer.parseInt(line.split("=")[1]);
				}
				helper = "wait";
				if(line.startsWith(helper)){
					waitBeforeReady = Integer.parseInt(line.split("=")[1]);
				}
				
			}
			else{
				try {
					fr.close();
				} catch (IOException e) {
					if(logger != null){
						logger.logError("Could not close fstream");
					}else{
//						new ErrorMessageGUI("Could not close fstream");
					}
				}
				break;
			}
		}
	}
	
	/**
	 * Returns server ip from the config file.
	 * @return
	 */
	public String getIp(){
		return ip;
	}
	
	/**
	 * Returns server port from the config file.
	 * @return
	 */
	public int getPort(){
		return port;
	}
	
	/**
	 * Returns waiting time from the config file.
	 * @return
	 */
	public int getWaitBeforeReady(){
		return waitBeforeReady;
	}
	
}
